/**
 * <p>Copyright:Copyright(c) 2019</p>
 * <p>Company:Professional</p>
 * <p>Package:ces.org.course.api.service</p>
 * <p>File:FileService.java</p>
 * <p>类更新历史信息</p>
 * @todo chanlong(陈龙) 创建于 May 20, 2019 3:40:55 PM
 */
package ces.org.course.api.service;

import java.io.File;
import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import ces.org.course.api.event.FileUploadEvent;
import ces.org.course.api.event.FileUploadMessage;
import ces.org.course.api.watch.FileListenerRunner;

/**
 * <p>描述: </p>
 * <p>Company: Professional</p>
 * @author chanlong(陈龙)
 * @date May 20, 2019 3:40:55 PM
 * @version 1.0.2019
 */
@Service
public class FileService {

	public String upload(final MultipartFile file) throws Exception {
		try {
			// 创建目标文件
			File dest = new File(upload + file.getOriginalFilename());
			// 文件上传
			file.transferTo(dest);
			//事件发送模式
			if(touchMethod.equalsIgnoreCase("event")) {
				// 创建事件
				ApplicationEvent event = new FileUploadEvent(this, FileUploadMessage.builder().code(200).message("file upload is successed").filePath(dest.getAbsolutePath()).build());
				// 事件发布
				publisher.publishEvent(event);
				//System.out.println();
				
			}else if(touchMethod.equalsIgnoreCase("auto")) {
				//文件变化监控模式
				fileListenerRunner.run();
			}
			return dest.getAbsolutePath();
		} catch (IllegalStateException | IOException e) {
			throw new RuntimeException(e);
		}
	}
	
	@Value("${ces.file.upload}")
	private String upload;
	@Value("${ces.touch.method}")
	private String touchMethod;
	
	@Autowired
	private ApplicationEventPublisher publisher;
	@Autowired
	private FileListenerRunner fileListenerRunner;
	
}
